package com.tianruan.dc.modules.sys.user.utils;

import com.alibaba.fastjson.JSONObject;
import com.tianruan.dc.common.utils.HttpUtils;
import com.tianruan.dc.modules.sys.user.entity.WXResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;


@Component
public class WXUtils implements Serializable {


    private static String appId;
    private static String secret;


    @Value("${wx.mini.appId}")
    public void setAppId(String appId) {
        WXUtils.appId = appId;
    }

    @Value("${wx.mini.secret}")
    public void setSecret(String secret) {
        WXUtils.secret = secret;
    }

    public static WXResponse code2Session(String code) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appid", appId);
        paramsMap.put("secret", secret);
        paramsMap.put("js_code", code);
        paramsMap.put("grant_type", "authorization_code");
        try {
            String responseString = HttpUtils.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code");
            WXResponse wxResponse = JSONObject.parseObject(responseString, WXResponse.class);
            return wxResponse;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

}
